//
//  UIView+ZHView.m
//  sc-cyan-ios
//
//  Created by lj on 2017/12/27.
//  Copyright © 2017年 greenbuilding. All rights reserved.
//

#import "UIView+ZHView.h"

@implementation UIView (ZHView)

- (void)setCenterX:(CGFloat)centerX{
    CGPoint center = self.center;
    center.x = centerX;
    self.center = center;
}

- (void)setCenterY:(CGFloat)centerY{
    CGPoint center = self.center;
    center.y = centerY;
    self.center = center;
}

- (CGFloat)centerX{
    return  self.center.x;
}

- (CGFloat)centerY{
    return  self.center.y;
}

- (CGFloat)right{
    return CGRectGetMaxX(self.frame);
}
- (CGFloat)bottom{
    return CGRectGetMaxY(self.frame);
}

- (void)setRight:(CGFloat)right{
    self.x = right - self.width;
}
- (void)setBottom:(CGFloat)bottom{
    self.y = bottom - self.height;
}

/**
 * 从xib创建view
 */
+ (instancetype)initWithXib{
    
    return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil] lastObject];
}

/**
 * 判断View是否显示在屏幕上
 */
- (BOOL)isDisplayedInScreen
{
    if (self == nil) {
        return FALSE;
    }
    
    CGRect screenRect = [UIScreen mainScreen].bounds;
    
    // 转换view对应window的Rect
    CGRect rect = [self convertRect:self.frame fromView:nil];
    if (CGRectIsEmpty(rect) || CGRectIsNull(rect)) {
        return NO;
    }
    
    // 若view 隐藏
    if (self.hidden) {
        return NO;
    }
    
    // 若没有superview
    if (self.superview == nil) {
        return NO;
    }
    
    // 若size为CGrectZero
    if (CGSizeEqualToSize(rect.size, CGSizeZero)) {
        return  NO;
    }
    
    // 获取 该view与window 交叉的 Rect
    CGRect intersectionRect = CGRectIntersection(rect, screenRect);
    if (CGRectIsEmpty(intersectionRect) || CGRectIsNull(intersectionRect)) {
        return NO;
    }
    
    return YES;
}

@end
